package model

import (
	"fmt"

	"github.com/silenceper/wechat"
	"github.com/wtf/mahjong/utils"
)

type User struct {
	Id                           int
	UniqueId                     string
	UnionId                      string
	Channel                      string
	Name                         string
	HeadImg                      string
	Status                       int
	Time                         int
	LastLoginTime                int
	VideoTimes                   int
	Gem                          int
	Back                         int
	Search                       int
	Bomb                         int
	Ext                          int
	Resume                       int
	Multiple                     int
	Collect                      int
	Signtime                     int
	MonthStart                   int
	SceneId1, SceneId2, SceneId3 int
	Coin                         int
	NewVersion                   int
	Version                      string
	Eight                        int
	Levels                       int
	Icon                         int
	InviteGet                    string
}

type Version struct {
	Version string
	Check   int
}

type PostLogin struct {
	UserId     int      `json:"userId"`
	Level      int      `json:"level"`
	ShareCode  string   `json:"share_code"`
	OpenId     string   `json:"open_id"`
	Check      int      `json:"check"`
	IsNew      int      `json:"isNew"`
	Money      int      `json:"money"`
	Click      int      `json:"click"`
	Amount     int      `json:"amount"`
	News       int      `json:"news"`
	Gem        int      `json:"gem"`
	Collect    int      `json:"collect"`
	Signin     int      `json:"signin"`
	Ad         int      `json:"ad"`
	Month      int      `json:"month"`
	Pay        int      `json:"pay"`
	Price      int      `json:"price"`
	Days       int      `json:"days"`
	Scene1     []int    `json:"scene_1"`
	Scene2     []int    `json:"scene_2"`
	Scene3     []int    `json:"scene_3"`
	SceneUse1  []int    `json:"sceneUse_1"`
	SceneUse2  []int    `json:"sceneUse_2"`
	SceneUse3  []int    `json:"sceneUse_3"`
	Coin       int      `json:"coin"`
	NewVersion int      `json:"new_version"`
	Eight      int      `json:"eight"`
	Channel    string   `json:"channel"`
	Balance    int      `json:"balance"`
	Stock      []string `json:"store_stock"`
	Opened     bool     `json:"store_opened"`
	StoreLevel int      `json:"store_level"`
	Completes  []bool   `json:"store_completes"`
	TaskData   []string `json:"store_taskData"`
	TaskLevel  []string `json:"store_taskLevel"`
	FoodLevel  int      `json:"food_level"`
}

func (user *User) Create() (id int, err error) {
	sql := "INSERT INTO users (unique_id, channel, status, time, lastLoginTime, gem, coin, versions) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(user.UniqueId, user.Channel, user.Status, user.Time, user.LastLoginTime, user.Gem, user.Coin, user.Version)
	if err != nil {
		fmt.Println(err)
		return
	}
	idx, err := res.LastInsertId()
	if err != nil {
		return
	}
	id = int(idx)
	return
}

func UserByUniqueId(uniqueId string) (user User, err error) {
	user = User{}
	err = Db.QueryRow("SELECT id, unique_id, union_id, name, head_img, status, time, levels, lastLoginTime, video_times, gem, back, search, bomb, ext, resume, multiple, collect, signtime, month_start, scene_id_1, scene_id_2, scene_id_3, coin, newVersion, eight, channel, icon FROM users WHERE unique_id = ?", uniqueId).Scan(&user.Id, &user.UniqueId, &user.UnionId, &user.Name, &user.HeadImg, &user.Status, &user.Time, &user.Levels, &user.LastLoginTime, &user.VideoTimes, &user.Gem, &user.Back, &user.Search, &user.Bomb, &user.Ext, &user.Resume, &user.Multiple, &user.Collect, &user.Signtime, &user.MonthStart, &user.SceneId1, &user.SceneId2, &user.SceneId3, &user.Coin, &user.NewVersion, &user.Eight, &user.Channel, &user.Icon)
	return
}

func InviteUniqueId(uniqueId string) (user User, err error) {
	user = User{}
	err = Db.QueryRow("SELECT id, unique_id, invite_get FROM users WHERE unique_id = ?", uniqueId).Scan(&user.Id, &user.UniqueId, &user.InviteGet)
	return
}

func Check(uniqueId string) (valid bool, err error) {
	user := User{}
	err = Db.QueryRow("SELECT id FROM users WHERE unique_id = ?", uniqueId).Scan(&user.Id)
	if err != nil {
		valid = false
		return
	}

	if user.Id > 0 {
		valid = true
	}
	return
}

func OpenIdByCode(code string) (openId string, unionId string, err error) {
	config := &wechat.Config{
		AppID:     utils.Config.AppId,
		AppSecret: utils.Config.AppSecret,
	}

	wc := wechat.NewWechat(config)
	auth := wc.GetOauth()

	res, err := auth.GetUserAccessTokenWG(code)
	if err != nil {
		return
	}

	openId = res.OpenID
	unionId = res.UnionId

	// 从池里获取连接
	rc := RedisClient.Get()
	// 用完后将连接放回连接池
	defer rc.Close()

	// 将session_key存入redis
	_, resErr := rc.Do("SET", utils.Config.PkgName+"_session_key:"+openId, res.SessionKey)
	if resErr != nil {
		utils.Error(resErr, "session_key更新失败"+res.SessionKey)
	}

	return
}

func OpenIdByUserId(userId int) (openId string, err error) {
	user := User{}
	err = Db.QueryRow("SELECT unique_id FROM users WHERE id = ?", userId).Scan(&user.UniqueId)
	openId = user.UniqueId
	return
}

func (user *User) Update(column string, value string) (err error) {
	statement := "UPDATE users SET " + column + " = ? WHERE unique_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(value, user.UniqueId)
	return
}

func UserById(userId int) (user User, err error) {
	user = User{}
	err = Db.QueryRow("SELECT id, unique_id, union_id, name, head_img, status, time, lastLoginTime, video_times, gem, back, search, bomb, ext, resume, multiple, collect, eight FROM users WHERE id = ?", userId).Scan(&user.Id, &user.UniqueId, &user.UnionId, &user.Name, &user.HeadImg, &user.Status, &user.Time, &user.LastLoginTime, &user.VideoTimes, &user.Gem, &user.Back, &user.Search, &user.Bomb, &user.Ext, &user.Resume, &user.Multiple, &user.Collect, &user.Eight)
	return
}

func FriendInfoById(openId string) (user User, err error) {
	user = User{}
	err = Db.QueryRow("SELECT name, head_img, icon FROM users WHERE unique_id like ?", openId).Scan(&user.Name, &user.HeadImg, &user.Icon)
	return
}

func GetVersion(versionxx string) (check int, err error) {
	versions := Version{}

	err = Db.QueryRow("SELECT checks FROM versions WHERE versions = ?", versionxx).Scan(&versions.Check)
	check = versions.Check
	return
}

func UnionIdByUniqueId(uniqueId string) (unionId string, err error) {
	err = Db.QueryRow("SELECT union_id FROM users WHERE unique_id = ?", uniqueId).Scan(&unionId)
	return
}

func GetCount(start, end int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM users WHERE time >= ? AND time <= ?", start, end).Scan(&count)
	return
}

func UpdateCoin(openId string, coin int) (err error) {
	statement := "UPDATE users SET coin = ? WHERE unique_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(coin, openId)
	return
}
